/*! 
 * WeX5 v3 (http://www.justep.com) 
 * Copyright 2015 Justep, Inc.
 * Licensed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) 
 */
define(function(require) {
	var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");
	var url = require.normalizeName("./wxAppPay");
	var WindowDialog = require("$UI/system/components/justep/windowDialog/windowDialog");
	var ComponentConfig = require("./wxAppPay.config");
	var Expr = justep.Express;
	require("res!../../config");
	require("res!./wxAppPayPage");
	require("w!./wxAppPayPage/paycode.w");
	require("res!../../admin");
	require("w!../../admin/order.w");
	require("w!../../admin/refund.w");
	require("w!../../admin/refundQuery.w");
	require("w!../../admin/weixin_cspz.w");
	require("w!../../admin/weixin_guanli.w");

	var dialogUrls = {
		// 微信支付二维码
		paycode: '{0}/wxAppPayPage/paycode.w'

	};

	function getUrl(name, appPath) {
		appPath = appPath || '$UI/comp/wxAppPay/components/wxAppPay';
		var url = justep.String.format(dialogUrls[name], appPath);
		return require.toUrl(url);
	}

	var wxAppPay = justep.BindComponent.extend({

		getDlgUrl: function(name) {
			return getUrl(name, this.getAppPath());
		},

		getConfig: function() {
			return ComponentConfig;
		},
		// 构造函数
		constructor: function(model, xid) {
			this.callParent();
			this.tradeType = "";
			this.limitPay = "";
			this.bodyExpr = "";
			this.outTradeNoExpr = "";
			this.totalFeeExpr = "";
			this.openidExpr = "";
			this.productIdExpr = "";
		},
		getAppPath: function() {
			var cfg = this.getConfig();
			return this.appPath || cfg.appPath;
		},
		openWindowDialog: function(option) {
			// option: src,params
			if (!this.dlg) {
				this.dlg = this._createWinDlg(option);
			}
			this.dlg.open(option);
			this.dlg.$domNode.find('.x-dialog').css('background-color', 'rgba(0,0,0,0.5)')
		},
		_createWinDlg: function(option) {
			var m = this.getModel();
			// 创建对话框
			var dlgCfg = {
				showTitle: false,
				src: option.src,
				parentNode: m.getRootNode()
			};
			var dlg = new WindowDialog(dlgCfg);
			return dlg;
		},

		// 微信支付二维码
		_openPage: function(url, orderNo) {
			this.openWindowDialog({
				"src": this.getDlgUrl('paycode'),
				"data": {
					"url": url,
					"orderNo": orderNo,
					"compObj": this
				}
			});
		},

		// 支付前事件
		_onPayBefore: function() {
			this.fireEvent('onPayBefore', {
				source: this
			});
		},

		// 支付成功事件
		_onPaySuccess: function(res) {
			this.fireEvent('onPaySuccess', {
				source: this,
				data: res
			});
		},

		// 支付失败事件
		_onPayFail: function() {
			this.fireEvent('onPayFail', {
				source: this
			});
		},

		// 微信内支付
		_wxPay: function(options) {
			console.log(options);
			var self = this;
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest', {
					"appId": options.appId, //公众号名称，由商户传入     
					"timeStamp": options.timeStamp, //时间戳，自1970年以来的秒数     
					"nonceStr": options.nonceStr, //随机串     
					"package": options.package,
					"signType": options.signType, //微信签名方式：     
					"paySign": options.paySign //微信签名 
				},
				function(res) {
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						self._onPaySuccess(res);
					}
					if(res.err_msg == "get_brand_wcpay_request:cancel"){
						self._onPayFail();
					}
					if(res.err_msg == "get_brand_wcpay_request:fail"){
						self._onPayFail();
					}
				}
			);
		},

		// 发起支付 
		sendPay: function() {
			var self = this;
			var options = {};
			var ctx = justep.Bind.contextFor(this.domNode);

			// 支付前事件
			this._onPayBefore();

			if (this.tradeType) {
				options.tradeType = this.tradeType;
			} else {
				justep.Util.hint('请根据您的应用场景选择交易类型！', {
					'type': 'warning'
				});
				return;
			}

			if (this.limitPay) {
				options.limitPay = this.limitPay;
			}

			if (this.bodyExpr) {
				if (!(this._bodyExpr instanceof Expr)) this._bodyExpr = new Expr(this.bodyExpr);
				options.body = Expr.eval(this._bodyExpr, ctx.$object, ctx);
				if(options.body == undefined){
					justep.Util.hint('商户描述不能为空!', {
						'type': 'warning'
					});
					return;
				}
			} else {
				justep.Util.hint('商户描述为必须参数！', {
					'type': 'warning'
				});
				return;
			}

			if (this.outTradeNoExpr) {
				if (!(this._outTradeNoExpr instanceof Expr)) this._outTradeNoExpr = new Expr(this.outTradeNoExpr);
				options.outTradeNo = Expr.eval(this._outTradeNoExpr, ctx.$object, ctx);
				if(options.outTradeNo == undefined){
					justep.Util.hint('商户内部订单号不能为空！', {
						'type': 'warning'
					});
					return;
				}
			} else {
				justep.Util.hint('商户内部订单号为必须参数！', {
					'type': 'warning'
				});
				return;
			}

			if (this.totalFeeExpr) {
				if (!(this._totalFeeExpr instanceof Expr)) this._totalFeeExpr = new Expr(this.totalFeeExpr);
				options.totalFee = Expr.eval(this._totalFeeExpr, ctx.$object, ctx);
				options.totalFee = parseFloat(options.totalFee) * 100; //微信接口最小单位为分
				if(options.totalFee == undefined){
					justep.Util.hint('金额不能为空！', {
						'type': 'warning'
					});
					return;
				}
			} else {
				justep.Util.hint('请在支付组件属性上设置金额！', {
					'type': 'warning'
				});
				return;
			}

			if (this.tradeType == "JSAPI") {
				if (this.openidExpr) {
					if (!(this._openidExpr instanceof Expr)) this._openidExpr = new Expr(this.openidExpr);
					options.openid = Expr.eval(this._openidExpr, ctx.$object, ctx);
					if(options.openid == undefined){
						justep.Util.hint('用户标识openid不能为空！', {
							'type': 'warning'
						});
						return;
					}
				} else {
					justep.Util.hint('交易类型为公众号支付时，用户标识不能为空！', {
						'type': 'warning'
					});
					return;
				}
			}

			if (this.tradeType == "NATIVE") {
				if (this.productIdExpr) {
					if (!(this._productIdExpr instanceof Expr)) this._productIdExpr = new Expr(this.productIdExpr);
					options.productId = Expr.eval(this._productIdExpr, ctx.$object, ctx);
					if(options.productId == undefined){
						justep.Util.hint('交易类型为扫码支付时，商品id不能为空！', {
							'type': 'warning'
						});
						return;
					}
				} else {
					justep.Util.hint('交易类型为扫码支付时，商品id不能为空！', {
						'type': 'warning'
					});
					return;
				}
			}

			
			// 微信统一下单
			$.ajax({
				type: "POST",
				contentType: "application/json;charset=UTF-8",
				dataType: "json",
				async: true,
				url: require.toUrl('/wxapi/mp/pay/unifiedOrder'),
				data: JSON.stringify(options),
				success: function(res) {
					var msg = res.msg;
		            if(msg.indexOf('<err_code_des>')>0){
		                msg = msg.split('<err_code_des><![CDATA[')[1].split(']]></err_code_des>')[0]
		            }

					if (res.success) {
						switch (self.tradeType) {
							case "NATIVE":
								self._openPage(res.data.codeUrl, options.outTradeNo, options.payType);
								break;
							case "JSAPI":
								if (typeof WeixinJSBridge == "undefined") {
									if (document.addEventListener) {
										document.addEventListener('WeixinJSBridgeReady', self._wxPay(res.data), false);
									} else if (document.attachEvent) {
										document.attachEvent('WeixinJSBridgeReady', self._wxPay(res.data));
										document.attachEvent('onWeixinJSBridgeReady', self._wxPay(res.data));
									}
								} else {
									self._wxPay(res.data);
								}
								break;
							case "MWEB":
								if (res.data.result_code == "SUCCESS") {
									window.open(res.data.mweb_url);
								}
								break;
						}

					} else {
						justep.Util.hint(msg, {
							'type': 'warning'
						});
					}

				},
				fail: function(res) {
					justep.Util.hint(res, {
						'type': 'warning'
					});
				}
			});
		}
	});

	justep.Component.addOperations(wxAppPay, {
		'sendPay': {
			label: '发起支付',
			argsDef: [],
			method: function(args) {
				return this.owner.sendPay();
			}
		}
	});

	justep.Component.register(url, wxAppPay);
	return wxAppPay;
});